<?php
namespace Wechat\Controller;

use Think\Controller;
use Com\Wechat;
use Com\WechatAuth;
use Think\Model;
class IndexController extends Controller
{

    private $wechat;

    public function _initialize()
    {
        header("Content-Type:text/html; charset=utf-8");
    }

    /**
     * 微信消息接口入口
     * 所有发送到微信的消息都会推送到该操作
     * 所以，微信公众平台后台填写的api地址则为该操作的访问地址
     */
    public function index()
    {
        try {
            $appid = C('WECHAT_APPID'); // AppID(应用ID)
            $token = C('WECHAT_TOKEN'); // 微信后台填写的TOKEN
            $crypt = C('WECHAT_CRYPT'); // 消息加密KEY（EncodingAESKey）
            $this->wechat = new Wechat($token, $appid, $crypt);
            $data = $this->wechat->request();
            if ($data && is_array($data)) {
                $this->reply($data);
            }
        } catch (\Exception $e) {
            trace(json_encode($e->getMessage()), '', 'ERR', true);
        }
    }

    /**
     * 回复
     *
     * @param array $data 接受到微信推送的消息
     */
    private function reply($data)
    {
        switch ($data['MsgType']) {
            case Wechat::MSG_TYPE_EVENT:
                switch ($data['Event']) {
                    case Wechat::MSG_EVENT_SUBSCRIBE:
                        $token = getAccessToken();
                        //trace($token, '', 'DEBUG', true);
                        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'), $token);
                        $userInfo = $auth->userInfo($data['FromUserName']);
                        //trace(json_encode($userInfo), '', 'DEBUG', true);
                        $member = D('Member');
                        $memberInfo = $member->where(array('openid' => $data['FromUserName']))->find();
                        $info = array();
                        $info['nickname'] = isset($userInfo['nickname']) ? $userInfo['nickname'] : '';
                        $info['gender'] = isset($userInfo['sex']) ? $userInfo['sex'] : 0;
                        $info['avatar'] = isset($userInfo['headimgurl']) ? $userInfo['headimgurl'] : '';
                        if ($memberInfo && isset($memberInfo['status'])) {
                            $info['member_id'] = $memberInfo['member_id'];
                            $info['status'] = 1;
                            $info['subscribe_time'] = $data['CreateTime'];
                            $info['update_time'] = time();
                        } else {
                            $info['openid'] = $data['FromUserName'];
                            $info['status'] = 1;
                            $info['vip_start_time'] = '0000-00-00';
                            $info['vip_end_time'] = '0000-00-00';
                            $info['subscribe_time'] = $data['CreateTime'];
                            $info['create_time'] = NOW_TIME;
                        }
                        $info['channel'] = isset($data['EventKey']) ?  $data['EventKey'] : '';
                        $info['member_id'] = $member->update($info);

                        // 关注送券
                        $sendCoupon = getConfig('send_coupon');
                        if ($sendCoupon) {
                            $couponID = getConfig('send_coupon_id');
                            $coupon = M('Coupon')->where(array('coupon_id' => $couponID, 'status' => 1))->find();

                            if (!empty($coupon)) {
                                $memberCoupon = M('MemberCoupon')->field('id')->where(array('member_id' => $info['member_id'], 'coupon_id' => $couponID))->find();
                                if (empty($memberCoupon)) {
                                    $getCoupon = addMemberCoupon($info['member_id'], $couponID, 0);
                                }
                            }
                        }

                        // 邀请送券
                        $inviteCoupon = getConfig('invite_coupon');
                        if ($inviteCoupon) {
                            $invite = M('MemberInvite')->where(['invite_member_id' => $info['member_id']])->find();
                            if (!empty($invite) && $invite['is_subscribe'] == 0) {
                                $couponID = getConfig('invite_coupon_id');
                                $coupon = M('Coupon')->where(array('coupon_id' => $couponID, 'status' => 1))->find();
                                if (!empty($coupon)) {
                                    $memberCoupon = M('MemberCoupon')->field('id')->where(array('member_id' => $invite['invite_member_id'], 'coupon_id' => $couponID))->find();
                                    if (empty($memberCoupon)) {
                                        $getCoupon = addMemberCoupon($invite['invite_member_id'], $couponID, 0);
                                        if ($getCoupon) {
                                            M('MemberInvite')->where(['invite_id' => $invite['invite_id']])->save(['is_subscribe' => 1]);
                                        }
                                    }
                                }
                            }
                        }

                        addWechatSubscribeLog($data);
                        $this->getSubscribeArticle($info['channel']);
                        break;
                    case Wechat::MSG_EVENT_UNSUBSCRIBE:
                        // 取消关注，记录日志
                        $result = D('Member')->where(array('openid' => $data['FromUserName']))->save( array( 'status' => 0 ) );
                        addWechatSubscribeLog($data);
                        break;
                    case Wechat::MSG_EVENT_CLICK:
                        // 点击菜单的事件
                        $reply = $this->getEvent($data['EventKey'], $data['FromUserName']);
                        break;
                    case Wechat::MSG_EVENT_SCAN:
                        // 已关注 扫带参数的二维码
                        $reply = $this->getEvent($data['EventKey'], $data['FromUserName']);
                        break;
                    default:
                        // 其他事件 列入切到微信
                        //$this->wechat->replyText("欢迎关注BuyTime!您的事件类型：{$data['Event']}，EventKey：{$data['EventKey']}");
                        break;
                }
                break;
            
            case Wechat::MSG_TYPE_TEXT:
                switch ($data['Content']) {
                    case '我要订餐':
                        $week = getWeek(time());
                        if (in_array($week, ['周一', '周二', '周三', '周四'])){
                            $this->wechat->replyText("http://t.cn/RiZZrUx 熊猫食堂午餐外卖");
                        }
                        break;
                    case '下单成功':
                        $week = getWeek(time());
                        if (in_array($week, ['周二', '周三', '周四'])){
                            $media_id = 'cSqwSFLcyJXGD6o5LkfXHVD-_TWTOGg-_M9Zwmb8L1U';
                            $this->wechat->replyImage($media_id);
                        }
                        break;
                    case '约吃饭':
                        $week = getWeek(time());
                        if ($week == '周四'){
                            $media_id = 'cSqwSFLcyJXGD6o5LkfXHcAuWKzdm2thyKcB3h5sw1I';
                            $this->wechat->replyImage($media_id);
                        }
                        break;
                    case 'news':
                        $articles = M('article')->where('status = 1')->limit(5)->order('article_id DESC')->select();
                        $news = array();
                        foreach ($articles as $val) {
                            if (empty($val['article_url']) || $val['article_url'] == 'http://'){
                                $url = C('SITE_URL') . 'home/article/show?id=' . $val['article_id'];
                            } else {
                                $url = $val['article_url'];
                            }
                            $news[] = array( $val['article_title'], $val['article_desc'], $url, $val['article_thumb'] );
                        }
                        $news[0] = isset($news[0]) ? $news[0] : array();
                        $news[1] = isset($news[1]) ? $news[1] : array();
                        $news[2] = isset($news[2]) ? $news[2] : array();
                        $news[3] = isset($news[3]) ? $news[3] : array();
                        $news[4] = isset($news[4]) ? $news[4] : array();
                        $this->wechat->replyNews($news[0], $news[1], $news[2], $news[3], $news[4]);
                        break;
                    default:
//                        $this->wechat->replyText("欢迎您关注buytime！您输入的内容是：{$data['Content']}");
                        break;
                }
                break;
            
            default:
                // code...
                break;
        }
    }

    public function importOpenid()
    {
        set_time_limit(0);
        $token = getAccessToken();
        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'), $token);
        $list = $auth->userGet();
        if ($list){
            $member = D('Member');
            foreach ($list['data']['openid'] as $val){
                echo $val . '|';
                $memberInfo = $member->where(array('openid' => $val))->find();
                if (empty($memberInfo)){
                    $info = array();
                    $info['openid'] = $val;
                    $info['status'] = 1;
                    $info['vip_start_time'] = '0000-00-00';
                    $info['vip_end_time'] = '0000-00-00';
                    $info['subscribe_time'] = NOW_TIME;
                    $result = $member->update($info);
                    dump($result);
                }
                echo '<br>';
            }
        }
    }

    /**
     * 菜单
     */
    public function menuCreate()
    {

        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));

//        $url = $auth->getRequestCodeURL(C('SITE_URL') . 'wechat/index/desc', 'desc', 'snsapi_userinfo');
//        $goodsUrl = $auth->getRequestCodeURL(C('SITE_URL') . 'wechat/index/goods', 'goods', 'snsapi_userinfo');
//        $vipUrl = $auth->getRequestCodeURL(C('SITE_URL') . 'wechat/index/vip', 'vip', 'snsapi_base');
//        $orderUrl = $auth->getRequestCodeURL(C('SITE_URL') . 'wechat/index/order', 'order', 'snsapi_base');
//        $couponUrl = $auth->getRequestCodeURL(C('SITE_URL') . 'wechat/index/coupon', 'coupon', 'snsapi_base');

        $subs1[] = array('type' => 'view', 'name' => '福利介绍', 'url' => C('SITE_URL') . 'wechat/index/desc');
        $subs1[] = array('type' => 'view', 'name' => '我的会员', 'url' => C('SITE_URL') . 'wechat/index/vip');

        $subs2[] = array('type' => 'view', 'name' => '我的订单', 'url' => C('SITE_URL') . 'wechat/index/order');
        $subs2[] = array('type' => 'view', 'name' => '我的礼券', 'url' => C('SITE_URL') . 'wechat/index/coupon');
        $subs2[] = array('type' => 'view', 'name' => '联系我们', 'url' => C('SITE_URL') . 'wechat/index/contact');

        $sub1 = array('type' => 'view', 'name' => '订午餐', 'url' => C('SITE_URL') . 'wechat/index/goods');
        $sub2 = array('name' => '会员福利', 'sub_button' => $subs1);
        $sub3 = array('name' => '我的', 'sub_button' => $subs2);

        $data = array();
        $data[] = $sub1;
        $data[] = $sub2;
        $data[] = $sub3;
        var_dump($data);
        $token = $auth->getAccessToken();
        $result = $auth->menuCreate($data);
        dump($result);
    }

    /**
     * 事件
     * 
     * @param string $taskevent  事件
     * @param string $openid 用户openid
     * @return array; 响应的数据
     */
    private function getEvent($event = '', $openid = '')
    {
        switch ($event) {
            case 'news':
                $articles = M('article')->where('status = 1')->limit(5)->order('article_id DESC')->select();
                $news = array();
                foreach ($articles as $val) {
                    $news[] = array($val['article_title'], $val['article_desc'], $val['article_url'], $val['article_thumb']);
                }
                $news[0] = isset($news[0]) ? $news[0] : array();
                $news[1] = isset($news[1]) ? $news[1] : array();
                $news[2] = isset($news[2]) ? $news[2] : array();
                $news[3] = isset($news[3]) ? $news[3] : array();
                $news[4] = isset($news[4]) ? $news[4] : array();
                $this->wechat->replyNews($news[0], $news[1], $news[2], $news[3], $news[4]);
                break;
            case 'contact':
                $this->wechat->replyText(getConfig('wechat_contact'));
                break;
            case 'contact':
                $this->wechat->replyText(getConfig('wechat_contact'));
                break;
        }
    }

    private function getSubscribeArticle($channel = '')
    {
        $articleNum = getConfig('article_num');
        if (empty($articleNum)) {
            $articleNum = 1;
        }
        $articles = M('article')->where('status = 1 AND is_subscribe = 1')->limit($articleNum)->order('article_id DESC')->select();
        $news = array();
        foreach ($articles as $val) {
            if (empty($val['article_url']) || $val['article_url'] == 'http://') {
                $url = C('SITE_URL') . 'home/article/show?id=' . $val['article_id'];
            } else {
                $url = $val['article_url'];
            }
            $news[] = array($val['article_title'], $val['article_desc'], $url, $val['article_thumb']);
        }

        if ($channel == 'qrscene_81'){
            $articleNum ++ ;
            array_unshift($news, array('领取免费午餐', '领取免费午餐，先到先得', C('SITE_URL') . 'wechat/index/card', 'http://wechat.baitime.cn/wechat/images/852355869568808484.jpg'));
        }

        $news[0] = isset($news[0]) ? $news[0] : array();
        $news[1] = isset($news[1]) ? $news[1] : array();
        $news[2] = isset($news[2]) ? $news[2] : array();
        $news[3] = isset($news[3]) ? $news[3] : array();
        $news[4] = isset($news[4]) ? $news[4] : array();
        switch ($articleNum) {
            case 1:
                $this->wechat->replyNews($news[0]);
                break;
            case 2:
                $this->wechat->replyNews($news[0], $news[1]);
                break;
            case 3:
                $this->wechat->replyNews($news[0], $news[1], $news[2]);
                break;
            case 4:
                $this->wechat->replyNews($news[0], $news[1], $news[2], $news[3]);
                break;
            case 5:
                $this->wechat->replyNews($news[0], $news[1], $news[2], $news[3], $news[4]);
                break;
            default:
                $this->wechat->replyNews($news[0], $news[1]);
                break;
        }

    }

    private function getSubscribeCoupon($openid = '')
    {
        $member = getMember($openid);
        if (empty($member)) {
            return false;
        }
        $news = array("优惠券领取成功通知", "终于等到你！10元优惠券已经放入你的账户啦！", C('SITE_URL') . 'wechat/index/getCoupon/?openid=' . $openid, '');
        $this->wechat->replyNews($news[0]);

    }


    public function coupon()
    {
        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
        if (!isset($_GET['code'])) {
            $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
            $url = $auth->getRequestCodeURL($baseUrl, 'coupon', 'snsapi_base');
            Header("Location: {$url}");
            exit();
        } else {
            $token = $auth->getAccessToken('code', $_GET['code']);
            if (isset($token['errcode'])) {
                $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
                $url = $auth->getRequestCodeURL($baseUrl, 'coupon', 'snsapi_base');
                Header("Location: {$url}");
            }
        }
        $member = getMember($token['openid'], false);
        if (!empty($member)) {
            $coupon = D('MemberCoupon')->getCouponList($member['member_id']);
        } else {
            $coupon = array();
        }
        $this->assign('coupon', $coupon);
        $this->display();
    }


    public function order()
    {
        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
        if (!isset($_GET['code'])) {
            $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
            $url = $auth->getRequestCodeURL($baseUrl, 'order', 'snsapi_base');
            Header("Location: {$url}");
            exit();
        } else {
            $token = $auth->getAccessToken('code', $_GET['code']);
            if (isset($token['errcode'])) {
                $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
                $url = $auth->getRequestCodeURL($baseUrl, 'order', 'snsapi_base');
                Header("Location: {$url}");
            }
        }
        $member = getMember($token['openid'], false);
        if (!empty($member)) {
            $unfinishOrderList = array();
            $unfinishOrder = M('Order')->field('order_id,order_sn,start_deliver_time,end_deliver_time,order_amount,store_id')->where(array('member_id' => $member['member_id'], 'order_state' => 2))->select();
            if (!empty($unfinishOrder)) {
                foreach ($unfinishOrder as $order) {
                    $unfinishOrderList[$order['order_id']]['order'] = $order;
                }
                $unfinishOrderGoods = M('OrderGoods')->where(array('order_id' => array('in', array_keys($unfinishOrderList))))->select();
                foreach ($unfinishOrderGoods as $goods) {
                    $goods['image'] = thumb($goods['goods_image'], 766, 100, 4);
                    $unfinishOrderList[$goods['order_id']]['goods'] = $goods;
                }
            }

            $finishOrderList = array();
            $finishOrder = M('Order')->field('order_id,order_sn,start_deliver_time,end_deliver_time,order_amount,store_id')->where(array('member_id' => $member['member_id'], 'order_state' => 4))->select();
            if (!empty($finishOrder)) {
                foreach ($finishOrder as $order) {
                    $finishOrderList[$order['order_id']]['order'] = $order;
                }
                $finishOrderGoods = M('OrderGoods')->where(array('order_id' => array('in', array_keys($finishOrderList))))->select();
                foreach ($finishOrderGoods as $goods) {
                    $goods['image'] = thumb($goods['goods_image'], 766, 100, 4);
                    $finishOrderList[$goods['order_id']]['goods'] = $goods;
                }
            }
        } else {
            $finishOrderList = array();
            $unfinishOrderList = array();
        }
        $store = getStoreList();
        $this->assign('store', $store);
        $this->assign('finishOrderList', $finishOrderList);
        $this->assign('unfinishOrderList', $unfinishOrderList);
        $this->display();
    }

    public function getCoupon()
    {
        $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
        if (!isset($_GET['code'])) {
            $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
            $url = $auth->getRequestCodeURL($baseUrl, 'getCoupon', 'snsapi_base');
            Header("Location: {$url}");
            exit();
        } else {
            $token = $auth->getAccessToken('code', $_GET['code']);
            if (isset($token['errcode'])) {
                $baseUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'];
                $url = $auth->getRequestCodeURL($baseUrl, 'getCoupon', 'snsapi_base');
                Header("Location: {$url}");
            }
        }
        $member = getMember($token['openid']);
        if (empty($member)) {
            $this->error('微信公众号搜索BUYTIME,关注即可领取优惠券');
        }
        $sendCoupon = getConfig('send_coupon');
        if ($sendCoupon) {
            $couponID = getConfig('send_coupon_id');
            $coupon = M('Coupon')->where(array('coupon_id' => $couponID, 'status' => 1))->find();
        }
        if (empty($coupon)) {
            $this->error('此活动已暂停');
        }
        $memberCoupon = M('MemberCoupon')->field('id')->where(array('member_id' => $member['member_id'], 'coupon_id' => $couponID))->find();
        if (empty($memberCoupon)) {
            $getCoupon = addMemberCoupon($member['member_id'], $couponID, 0);
        } else {
            $getCoupon = true;
        }
        $this->assign('getCoupon', $getCoupon);
        $this->assign('coupon', $coupon);
        $this->display();
    }

    public function sendCoupon()
    {
        $member = I('get.member');
        $memberID = intval(decrypt($member));
        $msg = array();
        if (empty($memberID)){
            $msg["code"] = 1;
            $msg["msg"] = '领取失败！';
            $this->ajaxReturn($msg);
        }
        $sendCoupon = getConfig('send_coupon');
        if (empty($sendCoupon)){
            $msg["code"] = 3;
            $msg["msg"] = '活动关闭！';
            $this->ajaxReturn($msg);
        }
        $couponID = getConfig('send_coupon_id');
        $coupon = M('MemberCoupon')->where(array('member_id' => $memberID, 'coupon_id' => $couponID  ))->find();
        if ($coupon){
            $msg["code"] = 2;
            $msg["msg"] = '领取失败，您已经领取过！';
        } else {

            $msg["code"] = 0;
            $msg["msg"] = '领取成功';
        }
        $this->ajaxReturn($msg);
    }


    public function activity()
    {
        $this->display();
    }

    public function card()
    {
        $member = session('member');
        if (empty($member)){
            $auth = new WechatAuth(C('WECHAT_APPID'), C('WECHAT_APPSECRET'));
            if (!isset($_GET['code'])){
                $baseUrl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'];
                $url = $auth->getRequestCodeURL($baseUrl , 'goods', 'snsapi_userinfo');
                Header("Location: {$url}");
                exit();
            } else {
                $token = $auth->getAccessToken('code', $_GET['code']);
            }
            $userInfo = $auth->getUserInfo($token['openid']);
//            $token['openid'] = 'o2uRPs44YHtX4NqbqicggQZdRC8g';
            $member = getMember($token['openid'], false);
        } else {
            $member = getMember($member['openid'], false);
        }

        if (empty($member)){
            $this->error('请先搜索公众号BUYTIME，关注BUYTIME。');
        }

        if (!empty($userInfo)) {
            D('Member')->updateMember($member['member_id'], $userInfo['nickname'], $userInfo['sex'], $userInfo['headimgurl']);
        }

        session('member', array('member_id' => $member['member_id'], 'openid' => $member['openid'], 'nickname' => $member['nickname'] ));

        $this->display();
    }

    public function submitCard()
    {
        $card = I('get.card');
        if (empty($card)){
            $this->error('无效的卡号');
        }
        $member = session('member');
        if (empty($member)) {
            $this->error('微信公众号搜索BUYTIME,关注即可领取优惠券');
        }
        $couponCard = M('CouponCard')->where(array('card_sn' => strtoupper($card), 'status' => 1))->find();
        if (empty($couponCard)){
            $this->error('无效的卡号或已被使用的卡号');
        }
        $memberCoupon = M('MemberCoupon')->where(array('coupon_id' => $couponCard['coupon_id'], 'member_id' =>  $member['member_id']))->find();
        if ($memberCoupon){
            $this->error('您已经领取过了，不能再领取，把机会让给别人吧');
        }

        $coupon = M('Coupon')->where(array('coupon_id' => $couponCard['coupon_id'], 'status' => 1))->find();
        if (empty($coupon)){
            $this->error('无效的卡号或已被使用的卡号');
        }
        if ($couponCard && $coupon){
            $model = D();
            try {
                $model->startTrans();
                M('CouponCard')->where(array('card_id' => $couponCard['card_id']))->save(array('status' => 0));
                addMemberCoupon($member['member_id'], $couponCard['coupon_id'], 0);
                M('CardLog')->add(array('member_id' => $member['member_id'], 'card_id' => $couponCard['card_id'], 'create_time' => NOW_TIME));
                $model->commit();
            } catch (\Exception $e) {
                $model->rollback();
                $this->error('系统忙，请重新领取。');
            }
        }
        $this->assign('coupon', $coupon);
        $this->display();
    }




    /**
     * 资源文件上传方法
     * @param  string $type 上传的资源类型
     * @return string       媒体资源ID
     */
    private function upload($type, $filename){
        $appid     = C('WECHAT_APPID'); // AppID(应用ID)
        $appsecret = C('WECHAT_APPSECRET');
        $token = session("token");
        if($token){
            $auth = new WechatAuth($appid, $appsecret, $token);
        } else {
            $auth  = new WechatAuth($appid, $appsecret);
            $token = $auth->getAccessToken();
            session(array('expire' => $token['expires_in']));
            session("token", $token['access_token']);
        }
        dump(session('token'));
        switch ($type) {
            case 'image':
                dump($filename);
                $media    = $auth->materialAddMaterial($filename, $type);
                break;
            case 'voice':
                $media    = $auth->materialAddMaterial($filename, $type);
                break;
            case 'video':
                $discription = array('title' => '视频标题', 'introduction' => '视频描述');
                $media       = $auth->materialAddMaterial($filename, $type, $discription);
                break;
            case 'thumb':
                $media    = $auth->materialAddMaterial($filename, $type);
                break;

            default:
                return '';
        }
        dump($media);
        if($media["errcode"] == 42001){ //access_token expired
            session("token", null);
            $this->upload($type, $filename);
        }

        return $media['media_id'];
    }

    public function upimg(){
        $f = $this->upload('image', PUBLIC_PATH . 'temp/4.jpg');
        echo $f;
        echo "<br>";
        $f = $this->upload('image', PUBLIC_PATH . 'temp/9.jpg');
        echo $f;
        echo "<br>";
    }

}